package br.com.manutencaocarro.activity;

import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import br.com.manutencaocarro.R;
import br.com.manutencaocarro.dao.RelatorioDAO;
import br.com.manutencaocarro.modelo.Peca;
import br.com.manutencaocarro.modelo.Relatorio;

public class GeraRelatorioActivity extends Activity 
{
	private Date inicialDate;
	private Date finalDate;
	private Integer idCarro;
	private ListView lista;
	private TextView totalGasto;

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lista_pecas_relatorio);
		lista = (ListView) findViewById(R.id.lista_pecas);
		totalGasto = (TextView) findViewById(R.id.totalGasto);
		
		Intent intent = getIntent();
		Relatorio relatorio = (Relatorio) intent.getSerializableExtra(getString(R.string.dadosrelatorio));
		inicialDate = relatorio.getDataInicio();
		finalDate = relatorio.getDataFim();
		idCarro = relatorio.getIdCarro();
		registerForContextMenu(lista);
	}
	
	@Override
	protected void onResume() 
	{
		super.onResume();
		carregaLista();
	}
	
	private void carregaLista() 
	{
		RelatorioDAO dao = new RelatorioDAO(this);
		List<Peca> pecas = dao.geraRelatorio( inicialDate, finalDate, idCarro );
		dao.close();

		if( pecas.size() > 0 )
		{
			int layout = android.R.layout.simple_list_item_1;
			ArrayAdapter<Peca> adapter = new ArrayAdapter<>(this, layout , pecas);
			lista.setAdapter(adapter);
			double total = 0;
			
			for( int i = 0; i < pecas.size(); i++ )
			{
				total = total + pecas.get(i).getValorPeca();
			}
			
			totalGasto.setText( String.valueOf(total) );
		} else {
			Toast.makeText(this, R.string.compra_nao_encontrada, Toast.LENGTH_LONG).show();
			finish();
		}
	}
}
